#include "HiCommonLog.hpp"

#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

const static int MAX_BUF_SIZE = 2048;
static bool isIgnore = true;

static void debug(const char* file, const char* function, int line, const char* log) {
	printf("[%s::%s-%d] %s", file, function, line, log);
}

static void writeLogWithCallback(const char* file,
                                 const char* function, int line, const char* fmt, va_list args);

static HI_RTP_DEBUG logFunc = ::debug;

void hi_set_debug(HI_RTP_DEBUG func) {
	logFunc = func;
	if (func != nullptr) {
		isIgnore = false;
	}
}

void hi_is_ignore_debug(bool ignore) {
	isIgnore = ignore;
	if (nullptr == logFunc) {
		isIgnore = true;
	}
}

void hi_debug(const char* file, const char* function, int line, const char* format, ...) {
	va_list arguments;
    va_start(arguments, format);
    writeLogWithCallback(file, function, line, format, arguments);
    va_end(arguments);
}

static void writeLogWithCallback(const char* file,
                                 const char* function, int line, const char* format, va_list args)
{
	if(nullptr == logFunc) {
		return;
	}
	
	if (isIgnore) {
		return;
	}
	
    char chArr[MAX_BUF_SIZE];
    ::memset(chArr, 0, sizeof(chArr));
    vsnprintf(chArr, MAX_BUF_SIZE, format, args);
	int len = strlen(chArr);
	if (len < MAX_BUF_SIZE - 2) {
		if (chArr[len - 1] != '\n') {
			chArr[len] = '\n';
			chArr[len + 1] = '\0';
		}
	}
	logFunc(file, function, line, chArr);
}

FunctionTrace::FunctionTrace(const char* _file, const char* _function, int _line) {
	if (isIgnore) {
		return;
	}
	if(nullptr == logFunc) {
		return;
	}
	
	this->file = _file;
	this->function = _function;
	hi_debug(_file, _function, _line, " enter\n");
}
FunctionTrace::~FunctionTrace() {
	if (isIgnore) {
		return;
	}
	
	if(nullptr == logFunc) {
		return;
	}
	
	hi_debug(file.c_str(), function.c_str(), 0, " leave\n");
}